package com.hlxj.license.client;

import com.hlxj.license.client.util.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @功能:【LicenseClient 】
 * @作者:代守诚
 * @日期:2019/5/21
 * @时间:11:23
 */
@Component
public class LicenseClient {

    @Value("${licenseServer.webUrl}")
    private String webUrl;
    @Value("${sslContext.keyStorePath}")
    private String keyStorePath;
    @Value("${sslContext.keyStorepass}")
    private String keyStorepass;

    public boolean verity(String uuid, String publiceKey) {

        FileUtil.createFile("publicKey", publiceKey);
        //用户利用公钥和uuid加密用户本机信息（包括到期时间），设置成本机的唯一标识
        String response = getSID(uuid, publiceKey);
        System.out.println("服务端返回的结果：" + response);

        Map<String, String> signMap = new HashMap<>();
        try{
            signMap = (HashMap<String, String>)JsonUtil.stringToObject(response, HashMap.class);
        }catch (Exception e) {
            e.printStackTrace();
        }

        boolean flag = verityAvailability(signMap, publiceKey);
        return flag;

    }

    private String getSID(String uuid, String publicKey) {
        String cpuid = SerialNumberUtil.getCPUSerial().toUpperCase().replace(" ", "");
        String mainboard = SerialNumberUtil.getMotherboardSN().toUpperCase().replace(" ", "");
//        String disk = SerialNumberUtil.getHardDiskSN("c").toUpperCase().replace(" ", "");
        String mac = SerialNumberUtil.getMac().toUpperCase().replace(" ", "");

//        String registerTime = DateUtil.getCurrentTime();
//        String endTime = DateUtil.getNewDateByYear(registerTime, addYear);

//        Map<String, String> infoMap = new HashMap<>();
//        infoMap.put("UUID", uuid);
//        infoMap.put("CPU", cpuid);
//        infoMap.put("MainBoard", mainboard);
//        infoMap.put("MAC", mac);
//        infoMap.put("registerTime", registerTime);
//        infoMap.put("endTime", endTime);

//        FileUtil.writeFile("info", infoMap);

        StringBuilder strBuilder = new StringBuilder();
        strBuilder.append("UUID").append("=").append(uuid).append(";");
        strBuilder.append("CPU").append("=").append(cpuid).append(";").append("Mainboard").append("=").append(mainboard).append(";");
        strBuilder.append("MAC").append("=").append(mac);

        byte[] data = strBuilder.toString().getBytes();
        byte[] encodedData = null;
        String encode = null;
        try {
            encodedData = RSAUtil.encryptByPublicKey(data, publicKey);
            System.out.println("*************：" + encodedData.length);
            encode = StringUtil.bytesToString(encodedData);
            System.out.println("加密后数据：" + encode);
        }catch (Exception e) {
            e.printStackTrace();
        }

        //调用服务端接口
        String response = null;
//        SSLContext sSLContext = null;
//        try {
//            SSLContext sSLContext = HttpClientTool.getSSLContext(keyStorePath, keyStorepass);
//            sSLContext = HttpClientTool.getSSLContext();
//        }catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println("****************************");
        try {
            response = HttpClientTool.postJson(null, webUrl, encode);
        }catch (Exception e) {
            e.printStackTrace();
        }

        return response;
    }

    //厂商将绑定的信息利用sign加密后返回给用户验证，确认无误后存入本地，确认激活
    private boolean verityAvailability(Map<String, String> signMap, String publicKey) {
        byte[] encodedData = StringUtil.stringToBytes(signMap.get("encodedData"));
        System.out.println(signMap.get("encodedData"));
        System.out.println(encodedData);
        String sign = (String)signMap.get("sign");
        boolean status = false;
        try{
            status = RSAUtil.verify(encodedData, publicKey, sign);
        }catch (Exception e) {
            e.printStackTrace();
        }

        FileUtil.createFile("computerInfo", signMap.get("encodedData"));

//        if(status) {
//            try {
//                byte[] decodedData = RSAUtil.decryptByPublicKey(encodedData, publicKey);
//                String target = new String(decodedData);
//                System.out.println("解密后: \r\n" + target);
//            }catch (Exception e) {
//                e.printStackTrace();
//            }
//
//        }

        return status;
    }


}
